package cocoaas3.Titanium{
	import jp.progression.casts.*;import jp.progression.commands.display.*;import jp.progression.commands.lists.*;import jp.progression.commands.managers.*;import jp.progression.commands.media.*;import jp.progression.commands.net.*;import jp.progression.commands.tweens.*;import jp.progression.commands.*;import jp.progression.data.*;import jp.progression.events.*;import jp.progression.loader.*;import jp.progression.*;import jp.progression.scenes.*;import jp.nium.core.debug.Logger;import caurina.transitions.*;import caurina.transitions.properties.*;
	import flash.events.*;import flash.display.*;import flash.system.*;import flash.utils.*;import flash.net.*;import flash.media.*;import flash.geom.*;import flash.text.*;import flash.media.*;import flash.system.*;import flash.ui.*;import flash.external.ExternalInterface;import flash.filters.*;
	import mx.utils.*;

	import flash.desktop.*;

	import org.osflash.signals.*;
	import org.osflash.signals.natives.*;

	import jp.noughts.progression.commands.*;

	import com.facebook.graph.FacebookMobile;
	import com.facebook.graph.utils.FacebookDataUtils;
	import com.sbhave.openUrl.URLUtils;


	public class Facebook extends EventDispatcher{

		private static const classConstructed:Boolean = classConstruct();
		private static function classConstruct():Boolean {
			// ここに初期化処理
			NativeApplication.nativeApplication.addEventListener( InvokeEvent.INVOKE, onInvoke );
			return true;
		}


		static public var loginComplete_sig:Signal = new Signal( Object );
		static private var invoke_nsig:NativeSignal = new NativeSignal( NativeApplication.nativeApplication, InvokeEvent.INVOKE, InvokeEvent )
		static public var appid:String; // 数字だけだが、長いと扱える数値の上限を超えるので文字列として扱う
		static public var permissions:Array;
		static public function get loggedIn():Boolean{
			var diskCache:SharedObject = SharedObject.getLocal("diskCache");
			var token:String = diskCache.data["token"];
			var dt:Date = diskCache.data["expDate"];
			if(token && dt && dt.time > (new Date()).time){
				return true;
			} else {
				return false;
			}
		}

		//
		// カスタム変数
		//
		static public var forceBrowser:Boolean = false;// facebook アプリがあってもを使わず、ブラウザで認証させるようにする？






		static public function authorize():void{
			var url:String = "fbauth://authorize";
			//var isFbAppAvailable:Boolean = URLUtils.instance.canOpenUrl(url);
			var isFbAppAvailable:Boolean = true;
			var ops:URLVariables = new URLVariables();
			ops["client_id"] = appid;
			ops["type"] = "user_agent";
			ops["redirect_uri"] = "fbconnect://success";
			ops["display"] = "touch";
			ops["sdk"] = "ios";
			if( permissions != null && permissions.length > 0 ){
				ops["scope"] = permissions.join(",");
			}
			if( !isFbAppAvailable || forceBrowser ){
				url = "https://m.facebook.com/dialog/oauth";
				ops["redirect_uri"] = "fb"+ appid +"://authorize";
			}

			invoke_nsig.addOnce( onInvoke )

			var req:URLRequest = new URLRequest(url);
			req.data = ops;
			req.method = URLRequestMethod.GET;
			navigateToURL( req );
		}


		static private function startUsingApi(session:Object, error:Object){
			var p:Object = new Object();
			p.limit = 0;
			FacebookMobile.api("/me",function(result:Object, fail:Object):void{
				if(null == fail){
					trace(result.name);
				}
			},p);
		}



		static private function onInvoke( e ):void{
			var str:String = e.arguments[0];
			Logger.info( "Facebook onInvoke "+ str )
			if( str && str.indexOf("fb"+ appid +"://") != -1 ){
				var vars:URLVariables = FacebookDataUtils.getURLVariables( e.arguments[0] );
				var accessToken:String = vars.access_token;
				if(!accessToken || accessToken == ""){
					Logger.info( "Facebook onInvoke login error" )
					var err:String = vars.error;
					
					if(err && err == "service_disabled_use_browser"){
						authorize();
					} else if (err && err == "service_disabled"){
						// We cant use SSO at all use the old FacebookMobile.init() and FacebookMobile.login()
					}
			
					var errCode:String = vars.error_code;
					var userDidCancel:Boolean = !errCode && (!err || err == "access_denied"); 
					
					if( userDidCancel ){
						// User cancelled the login and authentication
					} 
				} else { // Login was successful
					Logger.info( "Facebook onInvoke login success" )
					var expiresIn:int = int(vars.expires_in);
					
					if(expiresIn != 0){ // Everything went just well
						var expDate:Date = new Date();
						expDate.seconds += expiresIn;
						FacebookMobile.init( appid, startUsingApi, accessToken );
						// Store FB details in LSO
						var diskCache:SharedObject = SharedObject.getLocal("diskCache");
						diskCache.data["token"] = accessToken;
						diskCache.data["expDate"] = expDate;
						diskCache.flush();
						diskCache.close();
						diskCache = null;

						var slist:SerialList = new SerialList();
						slist.addCommand(
							new OpenfishRequestAir( "v1/users/external_account_login.json", URLRequestMethod.POST, {
								type: "facebook",
								token: accessToken
							} ),
							function(){
								Logger.info( ObjectUtil.toString(this.latestData) )
								loginComplete_sig.dispatch( this.latestData.response.users[0] )
							},
						null);
						slist.execute();
					}
				}
			}
		}


	}
}